import { usePlanAuthority } from './usePlanAuthority';

import { usePlanBaseApi } from './usePlanBaseApi';
import { watch, computed, ref, nextTick } from 'vue';
import _ from 'lodash';
export const usePortalPlanApi = (Variable, emit) => {
  const {
    currectPlan,
    modifyPlan,
    mappingProps,
    dataQueryID,
    pageID,
    sortCode,
    isReset,
    planIsChange,
    queryPlanList,
    $q,
    planName,
    targetName,
    changePlanFlag,
    showShare,
    proxyPlan,
    menuContent,
    openSubWarning,
    subPlan,
    TabsRef,
    renameProxy,
    showRenameDialog,
    saveAsPlan,
    isPublic,
    isDefault,
    showDialog,
    sharePlan,
    shareDetile,
    showShareDetil,
    PortalIsChange,
    planIsChanging,
    isIgnore,
    isCreate
  } = Variable;
  const { hasAuth, getSubStatus } = usePlanAuthority(Variable);
  const { getDefaultPlan,GetQueryPlanV2 } = usePlanBaseApi(Variable, emit,'');
  const getQueryPlanList = async () => {
    //@ts-ignore
    if (window.TFF) {
      // return Promise.resolve([
      //   {
      //     "ID": "886ea57e-e835-4668-bc60-3e76a5fe4657",
      //     "PageID": "c9985b2f-8a5c-42d9-bef9-4acfb190fbe4",
      //     "DQID": "",
      //     "Name": "代码审查",
      //     "PlanRange": 0,
      //     "IsSystem": false,
      //     "IsDefault": false,
      //     "IsAuth": true,
      //     "UserID": "5135a12e-43d4-406c-9f6a-9dbad362c6eb",
      //     "UserName": "周国庆",
      //     "SharedBy": "",
      //     "ShareUsers": null,
      //     "PlanOrder": 0,
      //     "TopTime": "0001-01-01 00:00:00",
      //     "DefaultView": 0,
      //     "PlanType": 0,
      //     "PortalId": "33ab7e62-a3d7-461f-a7ff-c8c9edcfe415",
      //     "PortalFilterContent": JSON.stringify({
      //       "MetricsTimeRange": {
      //         "StartTime": "2024/04/01",
      //         "EndTime": "2024/05/30",
      //         "Type": "Days",
      //         "Period": "Day",
      //         "Code": ""
      //       },
      //       "MetricsPublicParams": [
      //         {
      //           "ID": 'e45814fe-2d64-11ef-ad50-00163e047836',
      //           "Code": "",
      //           "Name": "电站",
      //           "ValueInfo": {
      //             "Value": [
      //               {
      //                 "Label": "龙海市仓头村充电站",
      //                 "Value": "77983b6d-3bef-4af1-852b-9fcb711c6385",
      //                 "Values": {
      //                   "Id": "77983b6d-3bef-4af1-852b-9fcb711c6385",
      //                   "Code": "3506810005",
      //                   "Name": "龙海市仓头村充电站"
      //                 }
      //               },
      //               {
      //                 "Label": "龙洲湾枢纽充电站",
      //                 "Value": "c302db9e-5869-4484-9684-1db815890085",
      //                 "Values": {
      //                   "Id": "c302db9e-5869-4484-9684-1db815890085",
      //                   "Code": "5001130007",
      //                   "Name": "龙洲湾枢纽充电站"
      //                 }
      //               },
      //               {
      //                 "Label": "龙泉茶店镇卫生院充电项目",
      //                 "Value": "1e27dfaf-6066-4508-bdc2-88a9bd2106c2",
      //                 "Values": {
      //                   "Id": "1e27dfaf-6066-4508-bdc2-88a9bd2106c2",
      //                   "Code": "5101120029",
      //                   "Name": "龙泉茶店镇卫生院充电项目"
      //                 }
      //               },
      //               {
      //                 "Label": "龙泉柏合镇卫生院充电项目",
      //                 "Value": "a594d19c-f382-453c-8fa6-3fce82592b3f",
      //                 "Values": {
      //                   "Id": "a594d19c-f382-453c-8fa6-3fce82592b3f",
      //                   "Code": "5101120031",
      //                   "Name": "龙泉柏合镇卫生院充电项目"
      //                 }
      //               }
      //             ],
      //             "Text": "龙海市仓头村充电站,龙洲湾枢纽充电站,龙泉茶店镇卫生院充电项目,龙泉柏合镇卫生院充电项目"
      //           }
      //         }
      //       ]
      //     })
      //   },
      //   {
      //     "ID": "886ea57e-e835-4668-bc60-3e76a5fe4658",
      //     "PageID": "c9985b2f-8a5c-42d9-bef9-4acfb190fbe4",
      //     "DQID": "",
      //     "Name": "代码审查002",
      //     "PlanRange": 0,
      //     "IsSystem": false,
      //     "IsDefault": true,
      //     "IsAuth": false,
      //     "UserID": "5135a12e-43d4-406c-9f6a-9dbad362c6eb",
      //     "UserName": "周国庆",
      //     "SharedBy": "",
      //     "ShareUsers": null,
      //     "PlanOrder": 0,
      //     "TopTime": "0001-01-01 00:00:00",
      //     "DefaultView": 0,
      //     "PlanType": 0,
      //     "PortalId": "60029e5c-2e4d-4bac-87f4-b00bfe90e586",
      //     "PortalFilterContent": JSON.stringify({
      //       "MetricsTimeRange": {
      //         "StartTime": "2024/07/01",
      //         "EndTime": "2024/07/30",
      //         "Type": "Days",
      //         "Period": "Day",
      //         "Code": ""
      //       }
      //     })
      //   }
      // ]);
      //@ts-ignore
      return TFF.common.ajax.getDataAsync({
        //@ts-ignore
        url: `${Funcs.FasRequestTagAdd(
          //@ts-ignore
          TFF.common.ajax.getServiceUrl('FASR-GetQueryPlanListV3'),
        )}`,
        type: 'post',
        data: {
          queryPlanFilter: JSON.stringify({
            DQID: dataQueryID.value,
            pageID: pageID.value, //window.pageMetaData.ID,
            sortCode: sortCode.value ? sortCode.value : 'PlanOrder',
            BusinessTag: Funcs.GetUrlQuery('BusinessTag')
          })
        },
      });
    } else {
      return new Promise(resolve => {
        resolve([]);
      });
    }
  };
  let OnChangeToPublishOtherComponentsTimer: any = null;
  const OnChangeToPublishOtherComponents = async () => {
    if (OnChangeToPublishOtherComponentsTimer) {
      window.clearTimeout(OnChangeToPublishOtherComponentsTimer);
      OnChangeToPublishOtherComponentsTimer = null;
    }
    OnChangeToPublishOtherComponentsTimer = window.setTimeout(async () => {
      if (!isReset.value) {
        //扩展支持onchange 事件
        emit('changed', {
          hasAuth: hasAuth(),
          status: getSubStatus(),
        });
      } else {
        planIsChange.value = false;
      }
      const BeforeQuery: any = {};
      emit('beforeQuery', BeforeQuery);

      if (BeforeQuery.hasOwnProperty('cancel') && BeforeQuery.cancel) {
        return;
      }
      //通知条件变更？？？
      mappingProps.PortalFilterInstance.setScheme(
        modifyPlan.value.PortalFilter
      );
    }, 200);
  };
  const UpdateQueryPlan = async (queryPlanTarget, params) => {
    //@ts-ignore
    if (window.TFF) {
      if (params.hasOwnProperty('Name')) {
        params.Name = params.Name.trim();
        if (!params.Name.trim()) {
          //@ts-ignore
          Funcs.Notify(
            $q.lang.selectHelper.warning,
            $q.lang.queryPlan.title.searchPlaceholder,
            'warning',
          );
          return;
        }
      }
      //@ts-ignore
      TFF.common.ajax
        .getDataAsync({
          //@ts-ignore
          url: `${Funcs.FasRequestTagAdd(
            //@ts-ignore
            TFF.common.ajax.getServiceUrl('FASR-UpdateQueryPlan'),
          )}`,
          type: 'post',
          data: {
            planID: queryPlanTarget.ID,
            param: JSON.stringify(params),
          },
        })
        .then(async () => {
          queryPlanList.value = await getQueryPlanList();
        })
        .catch(e => { });
    }
  };
  //新增或编辑
  const CreateOrUpdateQueryPlan = async (
    isSaveAs,
    queryPlanTarget,
    backupName,
  ) => {
    queryPlanTarget = _.cloneDeep(queryPlanTarget)
    queryPlanTarget = Object.assign({}, queryPlanTarget);
    let isEditTargetPlan = false
    if (queryPlanTarget.ID == modifyPlan.value.ID && queryPlanTarget.PortalId) {
      queryPlanTarget.PortalFilterContent = modifyPlan.value.PortalFilterContent
      isEditTargetPlan=true
    }
    if (isSaveAs) {
      delete queryPlanTarget.ID;
      delete queryPlanTarget.WarningID;
      delete queryPlanTarget.IsSystem;
      queryPlanTarget.IsAuth = true;
    }
    if (!queryPlanTarget.Name) {
      //@ts-ignore
      Funcs.Notify(
        $q.lang.selectHelper.warning,
        $q.lang.queryPlan.title.searchPlaceholder,
        'warning',
      );
      return;
    }
    queryPlanTarget.Name = queryPlanTarget.Name.trim();
    queryPlanTarget.DQID = dataQueryID.value;
    queryPlanTarget.PageID = pageID.value; //window.pageMetaData.ID
    //@ts-ignore
    if (window.TFF) {
      //@ts-ignore
      TFF.common.ajax
        .getDataAsync({
          //@ts-ignore
          url: `${Funcs.FasRequestTagAdd(
            //@ts-ignore
            TFF.common.ajax.getServiceUrl('FASR-CreateOrUpdateQueryPlanV2'),
          )}`,
          type: 'post',
          data: {
            queryPlan: JSON.stringify(queryPlanTarget),
            BusinessTag: Funcs.GetUrlQuery('BusinessTag')
          },
        })
        .then(async res => {
          if (res.state == 0) {
            //@ts-ignore
            Funcs.Notify(
              $q.lang.selectHelper.warning,
              $q.lang.queryPlan.notify.fail.format(
                isSaveAs
                  ? $q.lang.queryPlan.title.saveAs
                  : $q.lang.queryPlan.title.save,
                res.errmsg,
              ),
              'warning',
            );

            return;
          }
          //@ts-ignore
          Funcs.Notify(
            $q.lang.selectHelper.warning,
            $q.lang.queryPlan.notify.success.format(
              isCreate.value ? $q.lang.queryPlan.title.create : (isSaveAs
                ? $q.lang.queryPlan.title.saveAs
                : $q.lang.queryPlan.title.save)
            ),
            'success',
          );
          queryPlanList.value = await getQueryPlanList();

          let plan = queryPlanList.value.find(
            item => item.ID == res.queryPlanID,
          );
          plan = _.cloneDeep(plan)
          if(isSaveAs&&!isCreate.value&&isEditTargetPlan){
            plan.isfromSaveAs = true
          }
          modifyPlan.value = Object.assign({}, plan);
          currectPlan.value = Object.assign({}, plan);
          if (isCreate.value) {
            if (backupName) {
              planName.value = targetName.value;
            }
            //@ts-ignore
            window.saveAsCallback = null
            setTimeout(() => {
              isCreate.value = false
            }, 200)
            isCreate.value = false
            return
          }
          let callback: any = ''
          let portalContent: any = ''
          //@ts-ignore
          if (window.saveAsCallback) {
            //@ts-ignore
            callback = window.saveAsCallback
            //@ts-ignore
            window.saveAsCallback = ''
            //@ts-ignore
            if (mappingProps.portalComponent && window.Widget[mappingProps.portalComponent]) {
              //@ts-ignore
              portalContent = window.Widget[mappingProps.portalComponent].getCurrectInstance()
              //@ts-ignore
              if (portalContent && portalContent.PortletInstances) {
                //@ts-ignore
                portalContent.PortletInstances.forEach(element => {
                  element.Ext1 ? (element.Name = element.Ext1) : ''
                });
              }
            }

          }

          setTimeout(() => {
            if (callback) {
              //@ts-ignore
              // window.Widget[mappingProps.portalComponent].setInstance(portalContent)
            }
            //@ts-ignore
            if (window.Widget[mappingProps.portalComponent]) {
              //@ts-ignore
              window.Widget[mappingProps.portalComponent].closeEdit()

            }

            if (callback) {
              callback(modifyPlan.value.PortalId).then(async () => {
                await nextTick()
                planIsChange.value = false;
                PortalIsChange.value = false
                setTimeout(() => {
                 // portalContent.ID = modifyPlan.value.PortalId
                  //@ts-ignore
                 // window.Widget[mappingProps.portalComponent].setInstance(portalContent)
                  setTimeout(() => {
                    PortalIsChange.value = false
                    changePlanFlag.value = false;
                    isIgnore.value = false
                    planIsChange.value = false;
                  }, 300);

                  //@ts-ignore
                  // window.Widget[mappingProps.portalComponent].backup()
                  //@ts-ignore
                  // window.Widget[mappingProps.portalComponent].setInstanceId(modifyPlan.value.PortalId)
                }, 150);

                // window.Widget[mappingProps.portalComponent].setInstanceId(modifyPlan.value.PortalId)
              })
              return
            }
            planIsChange.value = false;
            PortalIsChange.value = false
          }, 100);

          if (backupName) {
            planName.value = targetName.value;
          }
        })
        .catch(e => {
          //@ts-ignore
          Funcs.Notify(
            $q.lang.selectHelper.warning,
            $q.lang.queryPlan.notify.fail.format(
              isSaveAs
                ? $q.lang.queryPlan.title.saveAs
                : $q.lang.queryPlan.title.save,
              e.message,
            ),
            'warning',
          );
        });
    }
  };
  //置顶
  const TopQueryPlan = async queryplan => {
    //@ts-ignore
    if (window.TFF) {
      const params = {
        topType: queryplan.TopTime == '0001-01-01 00:00:00' ? 0 : 1,
        planID: queryplan.ID,
      };
      //@ts-ignore
      await TFF.common.ajax
        .getDataAsync({
          //@ts-ignore
          url: `${Funcs.FasRequestTagAdd(
            //@ts-ignore
            TFF.common.ajax.getServiceUrl('FASR-TopQueryPlan'),
          )}`,
          type: 'post',
          params,
        })
        .then(async () => {
          queryPlanList.value = await getQueryPlanList();
        });
    }
  };
  //批量保存（拖拽调整顺序）
  const SaveQueryPlans = async queryplanList => {
    //@ts-ignore
    if (window.TFF) {
      //@ts-ignore
      queryPlanList.value = await TFF.common.ajax.getDataAsync({
        //@ts-ignore
        url: `${Funcs.FasRequestTagAdd(
          //@ts-ignore
          TFF.common.ajax.getServiceUrl('FASR-SaveQueryPlans'),
        )}`,
        type: 'post',
        data: {
          queryPlans: JSON.stringify(queryplanList),
        },
      });
    }
  };
  const deleteQueryPlan = async (planId) => {
    //@ts-ignore
    if (window.TFF) {
      //@ts-ignore
      await TFF.common.ajax.getDataAsync({
        //@ts-ignore
        url: `${Funcs.FasRequestTagAdd(
          //@ts-ignore
          TFF.common.ajax.getServiceUrl('FASR-DeleteQueryPlan'),
        )}`,
        type: 'post',
        data: {
          id: planId,
        },
      });
    }
  };
  const shareToOther = async (shareList, plan) => {
    const shareUsers = [];
    shareList
      ? shareList.forEach(item => {
        const obj = {
          UserID: item.UserID,
          UserName: item.RealName,
        };
        //@ts-ignore
        shareUsers.push(obj);
      })
      : [];
    //@ts-ignore
    if (window.TFF) {
      //@ts-ignore
      const data = await TFF.common.ajax.getDataAsync({
        //@ts-ignore
        url: `${Funcs.FasRequestTagAdd(
          //@ts-ignore
          TFF.common.ajax.getServiceUrl('FASR-ShareQueryPlan'),
        )}`,
        type: 'post',
        data: {
          queryPlan: JSON.stringify(plan),
          shareUsers: JSON.stringify(shareUsers),
          BusinessTag: Funcs.GetUrlQuery('BusinessTag')
        },
      });

      if (data.state == 1) {
        queryPlanList.value = await getQueryPlanList();
        modifyPlan.value.ShareUsers = shareUsers
        modifyPlan.value.PlanRange = 2
        //@ts-ignore
        Funcs.Notify(
          $q.lang.selectHelper.warning,
          $q.lang.queryPlan.notify.shareSuccess,
          'success',
        );
        const proxyplanIsChange = planIsChange.value
        modifyPlan.value.ShareUsers = shareUsers
        modifyPlan.value.PlanRange = 2
        nextTick(()=>{
          setTimeout(() => {
            planIsChange.value = proxyplanIsChange
          }, 0);

        })
        showShare.value = false;
      } else {
        return;
      }
    }
  };
  //同步多维视图

  //方案更新
  const updateAdvQuery = async (Model) => {
    const params: any = _.cloneDeep(Model)
    if (!params || !Object.keys(params).length) return

    let PortalFilterContent = modifyPlan.value?.PortalFilterContent
    if (!PortalFilterContent) {
      PortalFilterContent = JSON.stringify({})
    }
    PortalFilterContent = JSON.parse(PortalFilterContent)
    let noChange = true
    for (const key in params) {
      if (params[key] != _.get(PortalFilterContent, key)) {
        _.set(PortalFilterContent, key, params[key])
        noChange = false
      }

    }
    if (noChange) return
    changePlanFlag.value = true;
    planIsChange.value = true;
    modifyPlan.value.PortalFilterContent = JSON.stringify(PortalFilterContent)
  };
  let planChangeDelay = null;
  const queryPlanByOtherComponent = reset => {
    if (reset) {
      isReset.value = true;
      modifyPlan.value = JSON.parse(JSON.stringify(currectPlan.value));
      OnChangeToPublishOtherComponents();
      planIsChange.value = false;
      setTimeout(() => {
        planIsChange.value = false;
        isReset.value = false;
      }, 100);
      return;
    }
    // 获取筛选器Scheme
    const planChangeProxy = planIsChange.value;
    if (planChangeDelay) {
      window.clearTimeout(planChangeDelay);
      planChangeDelay = null;
    }
    proxyPlan.value = JSON.stringify(modifyPlan.value);

    setTimeout(() => {
      planIsChange.value = planChangeProxy;
    }, 10);
    const BeforeQuery = {
      cancel: false,
    };
    emit('beforeQuery', BeforeQuery);

    if (BeforeQuery.hasOwnProperty('cancel') && BeforeQuery.cancel) {
      //切换方案的时候主动清空

      return;
    }
    //筛选器自己check 不通过拦截请求
    OnChangeToPublishOtherComponents();
  };

  const planOperate = async (e, callback) => {
    if (e.type == 'sub') {
      menuContent.value.hide();
      openSubWarning.value = true;
      subPlan.value =
        e.plan.ID == modifyPlan.value.ID ? modifyPlan.value : e.plan;
    } else if (e.type == 'edit') {
      TabsRef.value.currentTabIndex = 0;
      modifyPlan.value = Object.assign({}, e.plan);
    } else if (e.type == 'rename') {
      renameProxy.value = Object.assign({}, e.plan);
      menuContent.value.hide();
      targetName.value = JSON.parse(JSON.stringify(e.plan)).Name;
      return (showRenameDialog.value = true);
    } else if (e.type == 'saveAs') {

      //@ts-ignore
      window.saveAsCallback = callback
      // @ts-ignore
      if (!window.saveAsCallback && e.plan.ID == modifyPlan.value.ID) {
        //@ts-ignore
        window.saveAsPlan = Object.assign({}, e.plan);
        //@ts-ignore
        return queryPlanSaveAs(false, false)
      }

      menuContent.value.hide();
      saveAsPlan.value = Object.assign({}, e.plan);
      const plan = Object.assign({}, e.plan);
      setTimeout(() => {
        //@ts-ignore
        window.saveAsPlan = null
        targetName.value = plan.Name + '_copy';
        if (isCreate.value) {
          targetName.value = $q.lang.queryPlan.title.myPlan
          if (queryPlanList.value.some(item => item.Name == $q.lang.queryPlan.title.myPlan)) {
            //@ts-ignore
            targetName.value += new Date().format('hhmmss')
          }
        }
        isPublic.value = plan.PlanRange == '0' && plan.IsAuth;
        isDefault.value = false;
        showDialog.value = true;
      }, 10);
      return;
    } else if (e.type == 'save') {
      //@ts-ignore
      //  if(!window.saveAsCallback){
      //   //@ts-ignore
      //   mappingProps.portalComponent && window.Widget[mappingProps.portalComponent] && window.Widget[mappingProps.portalComponent].rejestorCallBack()
      // }
      menuContent.value.hide();
      e.plan = Object.assign({}, e.plan);
      if (!e.plan.Name) {
        //@ts-ignore
        Funcs.Notify(
          $q.lang.selectHelper.warning,
          $q.lang.queryPlan.title.searchPlaceholder,
          'warning',
        );
        return;
      }
      queryPlanSave(false)
      // setTimeout(async () => {
      //   await CreateOrUpdateQueryPlan(false, e.plan, null);
      //   modifyPlan.value = Object.assign({}, e.plan);
      //   planIsChange.value = false;
      // }, 0);
    } else if (e.type == 'share') {
       if(!e.plan.ShareUsers||!e.plan.ShareUsers.length){
          let ShareUsers =  await GetQueryPlanV2(e.plan.ID)
          e.plan.ShareUsers = ShareUsers.ShareUsers||[]
        }
      sharePlan.value = e.plan;
      showShare.value = true;
    } else if (e.type == 'top') {
      TopQueryPlan(e.plan);
    } else if (e.type == 'default') {
      e.plan.IsDefault = !e.plan.IsDefault;
      await UpdateQueryPlan(e.plan, {
        Default: e.plan.IsDefault,
      });
    } else if (e.type == 'delete') {
      //@ts-ignore
      Funcs.Confirm(
        $q.lang.selectHelper.warning,
        $q.lang.queryPlan.dialog.deletePlan,
        async () => {
          await deleteQueryPlan(e.plan.ID);

          getQueryPlanList().then(res => {
            queryPlanList.value = res;
            if (
              e.plan.ID == modifyPlan.value.ID &&
              e.plan.ID == currectPlan.value.ID
            ) {
              modifyPlan.value = currectPlan.value = null;
            }
            if (!modifyPlan.value && !currectPlan.value) {
              getDefaultPlan();
            }
          });
        },
        () => { },
        true,
        { type: 'warning' },
      );
    } else if (e.type == 'moveDown' || e.type == 'moveUp') {
      const type = e.type == 'moveDown' ? 1 : -2;
      let Target = JSON.parse(JSON.stringify(queryPlanList.value));
      //当前位置
      const index = Target.findIndex(item => item.ID == e.plan.ID);
      //删除
      Target = Target.filter(item => item.ID != e.plan.ID);
      if (type == -2) {
        if (index - 1 <= 0) {
          Target.unshift(e.plan);
        } else {
          Target.splice(index - 1, 0, e.plan);
        }
      } else {
        Target.splice(index + 1, 0, e.plan);
      }

      await SaveQueryPlans(
        Target.map(item => {
          return {
            ID: item.ID,
            PlanRange: item.PlanRange,
            Name: item.Name,
          };
        }),
      );
      queryPlanList.value = Target;
    } else if (e.type == 'shareDetail') {
      if(!e.plan.ShareUsers||!e.plan.ShareUsers.length){
        let ShareUsers =  await GetQueryPlanV2(e.plan.ID)
        e.plan.ShareUsers = ShareUsers.ShareUsers||[]
      }
      menuContent.value.hide();
      shareDetile.value = e.plan;
      showShareDetil.value = true;
    }
  };
  const queryPlanSave = (formPortal) => {
    //如果来源是方案的话 重新触发 门户的相关方案
    //@ts-ignore
    if (!formPortal && window.Widget[mappingProps.portalComponent]) {
      //@ts-ignore
      window.Widget[mappingProps.portalComponent].savePortalPlanContent(true)
      return
    }
    //@ts-ignore
    CreateOrUpdateQueryPlan(false, window.saveAsPlan ? window.saveAsPlan : modifyPlan.value, null);
  };
  const queryPlanSaveAs = (callback, formPortal) => {
    //@ts-ignore
    if (!formPortal && window.Widget[mappingProps.portalComponent]) {
      //@ts-ignore
      window.Widget[mappingProps.portalComponent].savePortalPlanContent(false)
      return
    }
    //@ts-ignore
    planOperate({ type: 'saveAs', plan: window.saveAsPlan ? window.saveAsPlan : modifyPlan.value, isCreate: window.isSaveType }, callback);
    //@ts-ignore
    delete window.isSaveType
  };
  watch(() => planIsChanging.value, (val) => {
    if (val) {
      setTimeout(() => {
        planIsChanging.value = false
      }, 1000);
    }
  })
  const isLoadFinshed = () => {
    return mappingProps.portalComponent && window.Widget && window.Widget[mappingProps.portalComponent] && window.Widget[mappingProps.portalComponent].setInstanceId
  }
  const publishDataToPortal = async (newValue, oldValue)=>{

    if(window.saveAsCallback||newValue.isfromSaveAs) return
    const resData = {newValue, oldValue,cancel:false}
    emit('beforePubshDataToPortal',resData)
    if(resData.cancel) return
    if(!oldValue||newValue.ID!== oldValue.ID){
      //@ts-ignore
      window.Widget[mappingProps.portalComponent].setInstanceId('')
    }

    //@ts-ignore
    if (mappingProps.portalComponent && window.Widget && window.Widget[mappingProps.portalComponent]) {
      //@ts-ignore
      window.Widget[mappingProps.portalComponent].PublicParamChanged(filterExpression.value)
    }
    if(!oldValue||newValue.ID!== oldValue.ID){
      //@ts-ignore
      await window.Widget[mappingProps.portalComponent].setInstanceId(newValue.PortalId)
    }


  }

  //编辑方案 差异化监听
  watch(
    () => modifyPlan.value,
    (newValue, oldValue) => {
      //@ts-ignore
      if (window.planChangeDelayByWatch) {
        //@ts-ignore
        window.clearTimeout(window.planChangeDelayByWatch)
        //@ts-ignore
        window.planChangeDelayByWatch = null
      }
      //@ts-ignore
      window.planChangeDelayByWatch = window.setTimeout(async () => {
        //@ts-ignore
        if (!newValue || !newValue.ID) return;
        if(modifyPlan.value.isfromSaveAs){
          setTimeout(() => {
          delete modifyPlan.value.isfromSaveAs
          }, 300);
        }
        planIsChanging.value = true
        planName.value = newValue.Name;
        if (newValue.ID != oldValue?.ID) {
          if (mappingProps.planType == '1') {
            const businessTag = Funcs.GetQueryString('BusinessTag', window.location.href)
            try {
              Funcs.SetPageUserProfile({
                profileKey: {
                  Key: `QUERYPLAN_MANAGER_PORTAL`,
                  DynamicKey: `${dataQueryID?.value ? dataQueryID?.value.replace(/-/ig, '_') : ''}${businessTag && businessTag.replace(/-/ig, '_')} `,

                },
                PageID: pageID.value,
                profileValue: JSON.stringify(newValue),
              })
            } catch (error) {

            }


            // return
          }
          emit('change', newValue);
        } else {
          emit('changed', {
            hasAuth: hasAuth(),
            status: getSubStatus(),
          });
        }

        if (!oldValue || !oldValue.ID) {
          //@ts-ignore
          if (isLoadFinshed()) {
            publishDataToPortal(newValue, oldValue)
          } else {
            setTimeout(async () => {
              if (isLoadFinshed()) {
                publishDataToPortal(newValue, oldValue)
              }
            }, 300)
          }
          PortalIsChange.value = false
          changePlanFlag.value = false;
          planIsChange.value = false;
          return;
        }
        if (newValue.ID != oldValue?.ID) {
          //@ts-ignore
          if (isLoadFinshed()) {
            // //@ts-ignore
            // window.Widget[mappingProps.portalComponent].setInstanceId(newValue.PortalId)
            publishDataToPortal(newValue, oldValue)
            //@ts-ignore
            window.Widget[mappingProps.portalComponent].closeEdit()

          }
          PortalIsChange.value = false
          changePlanFlag.value = false;
          isIgnore.value = false
          planIsChange.value = false;
          return;
        }else{
          publishDataToPortal(newValue, oldValue)
        }

        if (!proxyPlan.value) {
          proxyPlan.value = JSON.stringify(newValue);
        }
        if (proxyPlan.value == JSON.stringify(newValue)) {
          return;
        }
        if (isReset.value||planIsChanging.value) return;

        proxyPlan.value = JSON.stringify(newValue);
        changePlanFlag.value = true;
        planIsChange.value = true;
      }, 100)
    },
    {
      immediate: true,
      deep: true,
    },
  );
  const filterExpression = computed(() => {
    const filter = modifyPlan.value && modifyPlan.value.PortalFilterContent ? modifyPlan.value.PortalFilterContent : ''
    if (!filter) {
      return {}
    }
    return JSON.parse(filter)
  });
  return {
    updateFilterComponent: () => { },
    getQueryPlanList,
    OnChangeToPublishOtherComponents,
    UpdateQueryPlan,
    CreateOrUpdateQueryPlan,
    TopQueryPlan,
    SaveQueryPlans,
    deleteQueryPlan,
    updateAdvQuery,
    shareToOther,
    queryPlanByOtherComponent,
    resetMixViewSort: () => { },
    filterExpression,
    sortExpression: '',
    planOperate,
    queryPlanSave,
    queryPlanSaveAs,
    synchronizationMixView: () => { },
    synchronizationFilter: () => { },
    publishDataToPortal
  };
};
